import { debounce } from '@/utils/index.js'
import { onBeforeUnmount, onMounted } from 'vue'

export default function(chart) {

  let $_sidebarElm = null;
  let $_resizeHandler = null;

  onMounted(() => {
    $_resizeHandler = debounce(() => {
      if (chart)  chart.resize()
    }, 100)
    $_initResizeEvent()
    $_initSidebarResizeEvent()
  })

  onBeforeUnmount(() => {
    $_destroyResizeEvent()
    $_destroySidebarResizeEvent()
  })

  function $_initResizeEvent() {
    window.addEventListener('resize', $_resizeHandler)
  }
  function $_destroyResizeEvent() {
    window.removeEventListener('resize', $_resizeHandler)
  }
  function $_sidebarResizeHandler(e) {
    if (e.propertyName === 'width') {
      $_resizeHandler()
    }
  }
  function $_initSidebarResizeEvent() {
    $_sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    $_sidebarElm && $_sidebarElm.addEventListener('transitionend', $_sidebarResizeHandler)
  }
  function $_destroySidebarResizeEvent() {
    $_sidebarElm && $_sidebarElm.removeEventListener('transitionend', $_sidebarResizeHandler)
  }

}